package com.cxg.fairy.ec.main.index.search;

import android.graphics.Color;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v7.widget.AppCompatButton;
import android.support.v7.widget.AppCompatTextView;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.SearchView;
import android.text.Spannable;
import android.text.SpannableString;
import android.text.style.AbsoluteSizeSpan;
import android.util.TypedValue;
import android.view.KeyEvent;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.blankj.utilcode.util.StringUtils;
import com.choices.divider.Divider;
import com.choices.divider.DividerItemDecoration;
import com.cxg.fairy.ec.main.search.SearchListDelegate;
import com.cxg.fairy.util.log.LatteLogger;
import com.cxg.fairy.util.toasty.Toasty;
import com.diabin.latte.ec.R;
import com.diabin.latte.ec.R2;
import com.cxg.fairy.delegates.LatteDelegate;
import com.cxg.fairy.net.RestClient;
import com.cxg.fairy.net.callback.ISuccess;
import com.cxg.fairy.ui.recycler.MultipleItemEntity;
import com.cxg.fairy.util.storage.LattePreference;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * Created by CFairy
 */

public class SearchDelegate extends LatteDelegate {

    @BindView(R2.id.rv_search)
    RecyclerView mRecyclerView = null;
    @BindView(R2.id.et_search_view)
    SearchView mSearchEdit = null;
    @BindView(R2.id.btn_hot_search_1)
    AppCompatTextView btn_1 = null;
    @BindView(R2.id.btn_hot_search_2)
    AppCompatTextView btn_2 = null;
    @BindView(R2.id.btn_hot_search_3)
    AppCompatTextView btn_3 = null;
    @BindView(R2.id.btn_hot_search_4)
    AppCompatTextView btn_4 = null;
    @BindView(R2.id.btn_hot_search_5)
    AppCompatTextView btn_5 = null;
    @BindView(R2.id.btn_hot_search_6)
    AppCompatTextView btn_6 = null;
    @BindView(R2.id.btn_hot_search_7)
    AppCompatTextView btn_7 = null;
    @BindView(R2.id.btn_hot_search_8)
    AppCompatTextView btn_8 = null;
    @BindView(R2.id.btn_hot_search_9)
    AppCompatTextView btn_9 = null;

    LatteDelegate delegate = null;

    @OnClick(R2.id.btn_hot_search_1)
    void onClickToSearcheListDelegate() {
        delegate = SearchListDelegate.create(btn_1.getText().toString());
        getSupportDelegate().start(delegate);
    }

    @OnClick(R2.id.btn_hot_search_2)
    void onClickToSearcheListDelegate2() {
        delegate = SearchListDelegate.create(btn_2.getText().toString());
        getSupportDelegate().start(delegate);
    }
    @OnClick(R2.id.btn_hot_search_3)
    void onClickToSearcheListDelegate3() {
        delegate = SearchListDelegate.create(btn_3.getText().toString());
        getSupportDelegate().start(delegate);
    }
    @OnClick(R2.id.btn_hot_search_4)
    void onClickToSearcheListDelegate4() {
        delegate = SearchListDelegate.create(btn_4.getText().toString());
        getSupportDelegate().start(delegate);
    }
    @OnClick(R2.id.btn_hot_search_5)
    void onClickToSearcheListDelegate5() {
        delegate = SearchListDelegate.create(btn_5.getText().toString());
        getSupportDelegate().start(delegate);
    }
    @OnClick(R2.id.btn_hot_search_6)
    void onClickToSearcheListDelegate6() {
        delegate = SearchListDelegate.create(btn_6.getText().toString());
        getSupportDelegate().start(delegate);
    }
    @OnClick(R2.id.btn_hot_search_7)
    void onClickToSearcheListDelegate7() {
        delegate = SearchListDelegate.create(btn_7.getText().toString());
        getSupportDelegate().start(delegate);
    }
    @OnClick(R2.id.btn_hot_search_8)
    void onClickToSearcheListDelegate8() {
        delegate = SearchListDelegate.create(btn_8.getText().toString());
        getSupportDelegate().start(delegate);
    }
    @OnClick(R2.id.btn_hot_search_9)
    void onClickToSearcheListDelegate9() {
        delegate = SearchListDelegate.create(btn_9.getText().toString());
        getSupportDelegate().start(delegate);
    }

    @OnClick(R2.id.btn_clear_history)
    void onClickClearHistory() {
        LattePreference.removeCustomAppProfile(SearchDataConverter.TAG_SEARCH_HISTORY);
        mRecyclerView.removeAllViews();
        List<MultipleItemEntity> data = null;
        SearchAdapter adapter = new SearchAdapter(data);
        mRecyclerView.setAdapter(adapter);
        mRecyclerView.getAdapter().notifyDataSetChanged();
    }

    @OnClick(R2.id.tv_top_search)
    void onCliclSearch() {
        doSearch();
    }

    private void doSearch() {
        final String searchItemText = mSearchEdit.getQuery().toString();
        String searchText = searchItemText.replaceAll("\\s*", "");
        if ("".equals(searchText)) {
            Toasty.error(getContext(), "请输入正确的搜索内容!").show();
        } else {
            saveItem(searchItemText);
            mSearchEdit.setQuery("", false);
            delegate = SearchListDelegate.create(searchItemText);
            getSupportDelegate().start(delegate);
        }
    }

    @OnClick(R2.id.icon_top_search_back)
    void onClickBack() {
        mSearchEdit.clearFocus();
        mSearchEdit.onActionViewCollapsed();
        getSupportDelegate().pop();
    }

    @SuppressWarnings("unchecked")
    private void saveItem(String item) {
        if (!StringUtils.isEmpty(item) && !StringUtils.isSpace(item)) {
            List<String> history;
            final String historyStr =
                    LattePreference.getCustomAppProfile(SearchDataConverter.TAG_SEARCH_HISTORY);
            if (StringUtils.isEmpty(historyStr)) {
                history = new ArrayList<>();
            } else {
                history = JSON.parseObject(historyStr, ArrayList.class);
            }
            history.add(item);
            final String json = JSON.toJSONString(history);

            LattePreference.addCustomAppProfile(SearchDataConverter.TAG_SEARCH_HISTORY, json);
        }
    }


    @Override
    public void onLazyInitView(@Nullable Bundle savedInstanceState) {
        super.onLazyInitView(savedInstanceState);
        // get hot words
        RestClient.builder()
                .url("getHotSearch")
                .loader(getContext())
                .success(new ISuccess() {
                    @Override
                    public void onSuccess(String response) {
                        LatteLogger.e("SearchDelegate.getHotSearchWords=", response);
                        final int code = JSON.parseObject(response).getInteger("code");
                        final String msg = JSON.parseObject(response).getString("message");
                        final JSONArray array = JSON.parseObject(response).getJSONArray("data");
                        btn_1.setText(array.getJSONObject(0).getString("keyword"));
                        btn_2.setText(array.getJSONObject(1).getString("keyword"));
                        btn_3.setText(array.getJSONObject(2).getString("keyword"));
                        btn_4.setText(array.getJSONObject(3).getString("keyword"));
                        btn_5.setText(array.getJSONObject(4).getString("keyword"));
                        btn_6.setText(array.getJSONObject(5).getString("keyword"));
                        btn_7.setText(array.getJSONObject(6).getString("keyword"));
                        btn_8.setText(array.getJSONObject(7).getString("keyword"));
                        btn_9.setText(array.getJSONObject(8).getString("keyword"));
                    }
                })
                .build()
                .post();
    }

    @Override
    public void onBindView(@Nullable Bundle savedInstanceState, @NonNull View rootView) {

        mSearchEdit.setFocusable(false);
        mSearchEdit.setFocusableInTouchMode(false);

        mSearchEdit.setIconified(false);
        mSearchEdit.setIconifiedByDefault(false);
        mSearchEdit.onActionViewExpanded();

        SpannableString spanText = new SpannableString("搜索新鲜水果");
        spanText.setSpan(new AbsoluteSizeSpan(14, true), 0, spanText.length(), Spannable.SPAN_INCLUSIVE_EXCLUSIVE);

        mSearchEdit.setQueryHint(spanText);

        TextView txt_search = (TextView) mSearchEdit.findViewById(android.support.v7.appcompat.R.id.search_src_text);
        txt_search.setTextSize(TypedValue.COMPLEX_UNIT_SP, 14);//14sp
        txt_search.setTextColor(Color.parseColor("#494949"));
        txt_search.setTextAlignment(View.TEXT_ALIGNMENT_CENTER);

        txt_search.setOnEditorActionListener(new TextView.OnEditorActionListener() {

            @Override
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                if (actionId == EditorInfo.IME_ACTION_SEND
                        || actionId == EditorInfo.IME_ACTION_DONE
                        || (event != null && KeyEvent.KEYCODE_ENTER == event.getKeyCode() && KeyEvent.ACTION_DOWN == event.getAction())) {
                    doSearch();
                }
                return false;
            }
        });


        final LinearLayoutManager manager = new LinearLayoutManager(getContext());
        mRecyclerView.setLayoutManager(manager);

        final List<MultipleItemEntity> data = new SearchDataConverter().convert();
        final SearchAdapter adapter = new SearchAdapter(data);
        mRecyclerView.setAdapter(adapter);

        final DividerItemDecoration itemDecoration = new DividerItemDecoration();
        itemDecoration.setDividerLookup(new DividerItemDecoration.DividerLookup() {
            @Override
            public Divider getVerticalDivider(int position) {
                return null;
            }

            @Override
            public Divider getHorizontalDivider(int position) {
                return new Divider.Builder()
                        .size(2)
                        .margin(20, 20)
                        .color(Color.GRAY)
                        .build();
            }
        });

        mRecyclerView.addItemDecoration(itemDecoration);

    }

    @Override
    public Object setLayout() {
        return R.layout.delegate_search;
    }


}
